// server.h
#ifndef SERVER_H
#define SERVER_H

#include <QObject>
#include <QTcpServer>
#include <QTcpSocket>
#include <QThread>
#include <QDebug>
#include <QDateTime>
#include <QMap>

class Server : public QObject
{
    Q_OBJECT
public:
    explicit Server(QObject *parent = nullptr);
    ~Server();
    void startServer(quint16 port);
    void stopServer();

signals:
    void newConnection(QTcpSocket *socket);

private slots:
    void onNewConnection();
    void onClientDisconnected();
    void onReadyRead();

private:
    QTcpServer *tcpServer;
    QMap<QTcpSocket*, QThread*> clientThreads; // 管理客户端连接的线程
};

class WorkerA : public QObject
{
    Q_OBJECT
public slots:
    void doWork(QTcpSocket *socket) {
        qDebug() << "Thread A started for socket:" << socket;
        
        while(socket && socket->state() == QTcpSocket::ConnectedState) {
            QThread::sleep(1);
            QString message = "Heartbeat from Thread A at " + QDateTime::currentDateTime().toString();
            if(socket->state() == QTcpSocket::ConnectedState) {
                socket->write(message.toUtf8());
                socket->flush();
            }
            QThread::yieldCurrentThread();
        }
        
        qDebug() << "Thread A finished for socket:" << socket;
        emit workFinished();
    }

signals:
    void workFinished();
};

#endif // SERVER_H
